﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using IntroduceCompany.Singleton;
using IntroduceCompany.DTO;
using System.Data.Linq;
using System.IO;
using IntroduceCompany.Util;
using System.Web.Security;

namespace IntroduceCompany.Models
{
    public class MenuListView_Validation
    {
        //[System.ComponentModel.DataAnnotations.MetadataType(typeof(IntroduceCompany.Models.MenuListView_Validation))]  put in Product class of linq

        [Required(ErrorMessage = "Name required")]
        [RegularExpression(ConstantClass.testNameOfMethod, ErrorMessage = "ControllerName không hợp lệ!")]
        public string ControllerName { get; set; }

        [Required(ErrorMessage = "Name required")]
        [RegularExpression(ConstantClass.testNameOfMethod, ErrorMessage = "ActionName không hợp lệ!")]
        public string ActionName { get; set; }
    }

    public class MenuListModels
    {


        /// <summary>
        /// Checking this function is open or not
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        internal bool AccepGoToFunctionManage(int adminID, String controlName, String actionName)
        {
            //Check this funtion is open or not (visible or not)
            if (DataSingleton.GetInstance().MenuListViews.Any(menu => menu.ControllerName == controlName && menu.ActionName == actionName && menu.MenuVisible == true))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Checking if this function is opened or not and check if user is disable or not
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        internal bool AcceptGoToFunctionManage(string userName,string _menuID)
        {
            if (userName.ToLower() == "superadmin" || userName=="")
            {
                return true;
            }
            else
            {
                if (DataSingleton.GetInstance().Administrators.SingleOrDefault(u => u.UserName == userName).Visible)
                {
                    if (DataSingleton.GetInstance().MenuListViews.Any(menu => menu.MenuListID == Convert.ToInt16(_menuID) && menu.MenuVisible == true))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else {
                    FormsAuthentication.SignOut();
                    return false;
                }
            }
        }


        /// <summary>
        /// Get All MenuList or based on language.
        /// </summary>
        /// <param name="languageID"></param>
        /// <returns></returns>
        public IQueryable<MenuListView> GetMenuList(String languageID, String menuTypeID)
        {
            if (languageID == ConstantClass.markViewAllLanguage)
            {
                if (menuTypeID == "")
                {
                    return DataSingleton.GetInstance().MenuListViews;
                }
                else
                {
                    return DataSingleton.GetInstance().MenuListViews.Where(MenuList => MenuList.MenuTypeID == menuTypeID);
                }
            }
            else
            {
                if (menuTypeID == "")
                {
                    return DataSingleton.GetInstance().MenuListViews.Where(MenuList => MenuList.LanguageID == languageID);
                }
                else
                {
                    return DataSingleton.GetInstance().MenuListViews.Where(MenuList => MenuList.LanguageID == languageID && MenuList.MenuTypeID == menuTypeID);
                }
            }
        }


        /// <summary>
        /// Get all menulist filter by language
        /// </summary>
        /// <returns></returns>
        internal List<MenuListView> GetMenuList(String languageID, int kind)
        {
            //Add menu "None" with ID = 0
            MenuListView tempMenu = new MenuListView();
            tempMenu.MenuListID = 0;
            tempMenu.MenuName = "None";
            List<MenuListView> menuList = new List<MenuListView>();
            menuList.Add(tempMenu);
            menuList.AddRange(DataSingleton.GetMenuListModels().GetMenuList(languageID, "").ToList());

            return (menuList);
        }


        /// <summary>
        /// Change Status of Menu that is visible or not
        /// </summary>
        /// <param name="menuListID"></param>
        /// <param name="menuVisible"></param>
        internal void ChangeMenuVisible(int menuListID, bool menuVisible)
        {
            MenuList menuList = DataSingleton.GetInstance().MenuLists.SingleOrDefault(menu => menu.MenuListID == menuListID);
            menuList.MenuVisible = (!menuVisible);
            DataSingleton.GetInstance().MenuLists.Context.SubmitChanges();
        }


        /// <summary>
        /// Delete a menu
        /// </summary>
        /// <param name="menuListID"></param>
        internal void DeleteMenuList(int menuListID, String fullImagePath)
        {
            MenuList menuList = DataSingleton.GetInstance().MenuLists.SingleOrDefault(menu => menu.MenuListID == menuListID);

            try
            {
                //Delete physical image of menu
                if (menuList.Image != "")
                {
                    string LocalFile = fullImagePath + menuList.Image;
                    if (File.Exists(LocalFile))
                        File.Delete(LocalFile);
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); };

            DataSingleton.GetInstance().MenuLists.DeleteOnSubmit(menuList);
            DataSingleton.GetInstance().MenuLists.Context.SubmitChanges();
        }


        /// <summary>
        /// Get a menu based on MenuListID
        /// </summary>
        /// <returns></returns>
        internal MenuListView GetMenuByID(int menuListID, String languageID)
        {
            return (DataSingleton.GetInstance().MenuListViews.SingleOrDefault(menu => menu.MenuListID == menuListID && menu.LanguageID == languageID));
        }


        /// <summary>
        /// Get Backend MenuList
        /// </summary>
        /// <returns></returns>
        internal IQueryable<MenuListView> GetBackEndMenuList()
        {
            return (DataSingleton.GetInstance().MenuListViews.Where(menu => menu.MenuBack_FontEnd == true && menu.LanguageID == "vi" && menu.MenuVisible == true)
                .OrderBy(menu => menu.Superior).OrderBy(menu => menu.Location));
        }


        /// <summary>
        /// Get Frontend MenuList filter by Language
        /// </summary>
        /// <returns></returns>
        internal IQueryable<MenuListView> GetFrontEndMenuList(String languageID)
        {
            return (DataSingleton.GetInstance().MenuListViews.Where(menu => menu.MenuBack_FontEnd == false && menu.MenuVisible == true && menu.LanguageID == languageID
                && menu.Superior == 0).OrderBy(menu => menu.Superior).OrderBy(menu => menu.Location));
        }


        /// <summary>
        /// Get All Frontend Menulist with HTML
        /// </summary>
        /// <param name="menuList"></param>
        /// <returns></returns>
        internal String GetAllFrontEndMenuListHtmlLink(String languageID, int menuListID)
        {

            IQueryable<MenuListView> subMenuListView = DataSingleton.GetInstance().MenuListViews
                .Where(menu => menu.MenuBack_FontEnd == false && menu.MenuVisible == true && menu.LanguageID == languageID && menu.Superior == menuListID)
                .OrderBy(menu => menu.Superior).OrderBy(menu => menu.Location);

            String result = "";
            if (subMenuListView.Count() > 0)
            {
                //Check CSS class only run one times
                if (menuListID == 0)
                {
                    result += "<ul class=\"menu\">";
                }
                else
                {
                    result += "<ul class=\"sub_menu\">";
                }

                foreach (var item in subMenuListView)
                {
                    if (item.MenuTypeID == "PRO" && item.Superior == 0)
                    {
                        result += "<li><a href=\"" + "/" + languageID + "/npr/" + item.MenuSeoUrl + "\">" + item.MenuName + "</a>";
                    }
                    else  if (item.MenuTypeID == "PRO" )
                    {
                        //result += "<li><a href=\"/" + item.ControllerName + "/" + item.ActionName + "/" + item.MenuListID +"\">" + item.MenuName + "</a>";
                        result += "<li><a href=\"" + "/" + languageID + "/pr/" + item.MenuSeoUrl + "\">" + item.MenuName + "</a>";
                    }
                    else if (item.MenuTypeID == "ART")
                    {
                        // result += "<li><a href=\"/vi/art/" + item.ControllerName + "/" + item.ActionName + "?articleTypeID=" + item.MenuListID + "&pageIndex=1\">" + item.MenuName + "</a>";
                        result += "<li><a href=\"/" + languageID + "/art/" + item.MenuSeoUrl + "\">" + item.MenuName + "</a>";
                        // result += "<li><a href=\"/vi/art/" + item.ControllerName + "/" + item.ActionName + "/" + item.MenuListID + "/1\">" + item.MenuName + "</a>";
                        //result += "<li><a href=\"/Danh-sach-san-pham" + "/" + item.MenuListID + "\">" + item.MenuName + "</a>";
                        //result += "<li><a href=\"/vi/ar" + "/" + item.MenuListID + "/1\">" + item.MenuName + "</a>";
                    }
                    else if (item.MenuTypeID == "ALB")
                    {
                        result += "<li><a href=\"/" + languageID + "/alb/" + item.MenuSeoUrl + "\">" + item.MenuName + "</a>";
                        //  result += "<li><a href=\"/" + languageID + "/alb/" + item.MenuSeoUrl + "\">" + item.MenuName + "</a>";
                    }
                    else if (item.MenuTypeID == "VID")
                    {
                        result += "<li><a href=\"/" + languageID + "/vid/" + item.MenuSeoUrl + "\">" + item.MenuName + "</a>";
                    }
                    else if (item.MenuTypeID == "FEE")
                    {
                        result += "<li><a href=\"/" + languageID + "/Feedback\">" + item.MenuName + "</a>";
                    }
                    else if (item.MenuTypeID == "SUR")
                    {
                        result += "<li><a href=\"" + "/" + languageID + "/sur/" + item.MenuSeoUrl + "\">" + item.MenuName + "</a>";
                    }
                    else if (item.MenuTypeID == "UNK")
                    {
                        result += "<li><a href=\"" + "/" + languageID + "/unk/" + item.MenuSeoUrl + "\">" + item.MenuName + "</a>";
                    }

                    result += GetAllFrontEndMenuListHtmlLink(languageID, item.MenuListID);

                    result += "</li>";
                }
                result += "</ul>";
            }
            return result;
        }



        /// <summary>
        /// Updatte MenuList
        /// </summary>
        /// <param name="menuListView"></param>
        internal void EditMenuList(MenuListView menuListView, String imageFileName)
        {
            MenuList menuList = DataSingleton.GetInstance().MenuLists.SingleOrDefault(menu => menu.MenuListID == menuListView.MenuListID);
            menuList.MenuTypeID = menuListView.MenuTypeID;
            menuList.ControllerName = menuListView.ControllerName.Trim();
            menuList.ActionName = menuListView.ActionName.Trim();
            menuList.Superior = menuListView.Superior;
            menuList.MenuBack_FontEnd = menuListView.MenuBack_FontEnd;
            menuList.Location = menuListView.Location;
            menuList.ArticleSingle = menuListView.ArticleSingle;
            if (imageFileName != null && imageFileName != "")
            {
                menuList.Image = imageFileName;
            }


            MenuList_L menuList_L = DataSingleton.GetInstance().MenuList_Ls.SingleOrDefault(menuL => menuL.MenuListID == menuListView.MenuListID
                && menuL.LanguageID == menuListView.LanguageID);
            menuList_L.MenuName = menuListView.MenuName.Trim();

            //DataSingleton.GetInstance().SubmitChanges();
            DataSingleton.GetInstance().MenuList_Ls.Context.SubmitChanges();
            DataSingleton.GetInstance().MenuLists.Context.SubmitChanges();

            DataSingleton.GetInstance().Refresh(RefreshMode.KeepChanges, menuList_L);

        }


        /// <summary>
        /// Get MenuType
        /// </summary>
        /// <returns></returns>
        internal IQueryable<MenuType> GetMenuType()
        {
            return (DataSingleton.GetInstance().MenuTypes);
        }


        /// <summary>
        /// Insert MenuList in first times
        /// </summary>
        /// <param name="menuListView"></param>
        /// <param name="languageID"></param>
        internal int MenuListCreate_1(MenuListView menuListView, String imageFileName)
        {

            var result = DataSingleton.GetInstance().sp_MenuListInsert(menuListView.MenuTypeID, menuListView.ControllerName.Trim(), menuListView.ActionName.Trim(),
                menuListView.Superior, menuListView.MenuBack_FontEnd, menuListView.Location, imageFileName, menuListView.ArticleSingle);

            int menuListMaxID = Convert.ToInt16(result.ToString());

            DataSingleton.GetInstance().sp_MenuList_L_Insert(menuListMaxID, menuListView.LanguageID, menuListView.MenuName.Trim());

            return menuListMaxID;
        }


        /// <summary>
        /// Insert MenuList_L
        /// </summary>
        /// <param name="menuListView"></param>
        /// <param name="languageID"></param>
        internal Boolean MenuListCreate_2(int menuListID, String languageID, String menuName)
        {
            try
            {
                DataSingleton.GetInstance().sp_MenuList_L_Insert(menuListID, languageID, menuName.Trim());
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// Get Article Type from MenuList
        /// </summary>
        /// <param name="languageID"></param>
        /// <returns></returns>
        public IQueryable<MenuListView> GetArticleType(String languageID)
        {
            return DataSingleton.GetInstance().MenuListViews.Where(u => u.MenuTypeID == "ART" && u.LanguageID == languageID);
        }





        /// <summary>
        /// Check a menu that has specific language or not.
        /// </summary>
        /// <param name="menuListView"></param>
        /// <returns></returns>
        internal bool CheckMenuListLanguage(MenuListView menuListView)
        {
            return (DataSingleton.GetInstance().MenuList_Ls.Any(menu => menu.MenuListID == menuListView.MenuListID && menu.LanguageID == menuListView.LanguageID));
        }


        /// <summary>
        /// Get MenuName filter by language and MenuSeoUrl 
        /// </summary>
        /// <param name="menuSeoUrl"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        internal String GetMenuTypeName(int menuListID, String languageID)
        {
            return DataSingleton.GetInstance().MenuListViews.First(menu => menu.MenuListID == menuListID && menu.LanguageID == languageID).MenuName;
        }


        /// <summary>
        /// Get MenuListID based on MenuSeoUrl
        /// </summary>
        /// <param name="menuSeoUrl"></param>
        /// <returns></returns>
        internal int GetMenuListIDByMenuSeoUrl(String menuSeoUrl)
        {

            if (DataSingleton.GetInstance().MenuList_Ls.Any(menu => menu.MenuSeoUrl == menuSeoUrl))
            {
                return DataSingleton.GetInstance().MenuList_Ls.First(menu => menu.MenuSeoUrl == menuSeoUrl).MenuListID;
            }
            else { return 0; }
        }




        internal bool CheckMenuList_WithLanguage(int articleTypeID, string LanguageID)
        {
            return DataSingleton.GetInstance().MenuList_Ls.Any(u => u.MenuListID == articleTypeID && u.LanguageID ==LanguageID);
        }

        /// <summary>
        /// get menu SEO_URL by MenuListID and LanguageID
        /// </summary>
        /// <param name="articleTypeID"></param>
        /// <param name="languageID"></param>
        /// <returns>article type SEO_URL</returns>
        internal string GetMenuSEO_URL_By_MenuListID_LanguageID(string menuListID, string languageID)
        {
            try
            {
                return DataSingleton.GetInstance().MenuListViews.SingleOrDefault(u => u.MenuListID == Convert.ToInt16(menuListID) && u.LanguageID == languageID && u.MenuVisible == true).MenuSeoUrl;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }

       

        /// <summary>
        /// get the all superior menuIDs of a menuID 
        /// </summary>
        /// <param name="menuID"></param>
        /// <returns></returns>
        private string GetSuperiorMenuID(int menuID) 
        {
            string str_MenuID = "";
            int superiorArticleTypeID = DataSingleton.GetInstance().MenuLists
                                        .SingleOrDefault(u => u.MenuListID == menuID).Superior;
            str_MenuID += menuID + ",";

            if (superiorArticleTypeID != 0)
            {
                str_MenuID += GetSuperiorMenuID(superiorArticleTypeID);
            }
            return str_MenuID;
        }



        internal string BuildSiteMapPath(string current_Url, string languageID)
        {
            string result = "";
            var arr_Url = current_Url.Split(new char[] { '/' });

            if (arr_Url.Length > 3)
            {
                int menuID = DataSingleton.GetMenuListModels().GetMenuListIDByMenuSeoUrl(arr_Url[3]);

                if (menuID != 0)
                {
                    string str_MenuID = GetSuperiorMenuID(menuID);
                    var arr_MenuID = str_MenuID.Split(new char[] { ',' });
                    MenuListView menu_temp;
                    for (int i = (arr_MenuID.Length - 2); i >= 0; i--)
                    {
                        menu_temp = DataSingleton.GetInstance().MenuListViews.SingleOrDefault(u => u.MenuListID == Convert.ToInt16(arr_MenuID[i]) && u.LanguageID == languageID);
                        if (menu_temp.MenuTypeID == "PRO" && menu_temp.Superior == 0)
                        {
                            result += "<a href=\"" + "/" + languageID + "/npr/" + menu_temp.MenuSeoUrl + "\">" + menu_temp.MenuName + "</a>";
                        }
                        else if (menu_temp.MenuTypeID == "PRO")
                        {
                            result += "<a href=\"" + "/" + languageID + "/pr/" + menu_temp.MenuSeoUrl + "\">" + menu_temp.MenuName + "</a>";
                        }
                        else if (menu_temp.MenuTypeID == "ART")
                        {
                            result += "<a href=\"/" + languageID + "/art/" + menu_temp.MenuSeoUrl + "\">" + menu_temp.MenuName + "</a>";
                        }
                        else if (menu_temp.MenuTypeID == "ALB")
                        {
                            result += "<a href=\"/" + languageID + "/alb/" + menu_temp.MenuSeoUrl + "\">" + menu_temp.MenuName + "</a>";
                        }
                        else if (menu_temp.MenuTypeID == "VID")
                        {
                            result += "<a href=\"/" + languageID + "/vid/" + menu_temp.MenuSeoUrl + "\">" + menu_temp.MenuName + "</a>";
                        }
                        else if (menu_temp.MenuTypeID == "FEE")
                        {
                            result += "<a href=\"/" + languageID + "/Feedback/\">" + menu_temp.MenuName + "</a>";
                        }
                    }
                }

                if (arr_Url[3] == "Feedback")
                {
 
                }

            }
            return result;
        }

        
    }
}